<template>
  <div>
    <el-card class="search-card">
      <BasicForm
        ref="formData"
        defaultExpandStatus
        formItemWidth="130px"
        :formColumns="formItems"
        :dataSource="formData"
        :handleSearchForm="handleQueryForm"
        @getFormData="getFormData"
      />
    </el-card>
    <el-card class="table-card">
      <skus-table
        ref="skusTable"
        showActionCol
        showPagination
        :tableHeight="480"
        :actionColWidth="200"
        :defaultMinWidth="100"
        :dataSource="TableInfo.list"
        :columns="TableInfo.columns"
        :loading="TableInfo.loading"
        :pageSizes="pageSizes"
        :pagination="pagination"
        :total="pagination.total"
        :actionRender="renderTableBtnAction"
        @pageChange="handlePageChange"
        @pageSizeSelect="handlePageSizeChange"
      >
        <!-- 按钮操作栏 -->
        <BtnRender slot="content_context" :render="renderBtnsBar" />
      </skus-table>
    </el-card>
    <!-- 取消开发弹框 -->
    <InputReasonDialog
      dialogTitle="取消开发"
      warningMsg="请填写取消开发计划原因"
      :visible.sync="planCancel.visible"
      :submit-loading="planCancel.loading"
      :input-maxlength="500"
      :handleSubmit="confirmPlanCancel"
    />
  </div>
</template>
<script>
import BasicForm from '@/components/BasicForm';
import SkusTable from '@/components/skusTable';
import BtnRender from '@/components/JSXRender/BtnRender';
import CategoryMultipleSelect from '@/components/Category/MultipleSelect';
import InputReasonDialog from '@/components/InputReasonDialog';
import { getListPageBtnsBar, getTableAction } from '@/utils/getBtnsRender';
import {
  FORM_ITEMS,
  TABLE_COLUMNS,
  RECORD_STATUS_VALUES,
  getStatusColumn,
  getSupplierInspectionNoColumn
} from './constants';
import skusPage from '@/mixins/commodity/skusPage';
import { getInitFormData, TableInfo } from '@/utils/getUtils';
import { setAuthBtnId, isResponseSuccess, createExcelByExport, generateUuid, } from '@/utils/bizUtils';
import {
  getPagerService,
  getBackWorkflow4DevPlanService,
  cancelService,
  getSupplierInspectionByReportCodeService,
  devPlanExportService
} from '@/api/commodity/developmentRequirementPlan/developPlan';
import { getToSkipOAUrlService } from '@/api/commodity/common';
export default {
  mixins: [skusPage],
  components: {
    BasicForm,
    SkusTable,
    BtnRender,
    CategoryMultipleSelect,
    InputReasonDialog,
  },
  data () {
    return {
      formItems: FORM_ITEMS,
      formData: getInitFormData(FORM_ITEMS),
      TableInfo: new TableInfo({ columns: this.getTableColumns() }),
      btnLoading: {
        export: false,
      },
      pageSizes: [10, 100, 1000],
      planCancel: {
        visible: false,
        loading: false,
        planNo: ''
      }
    }
  },
  mounted () {
    this.executeToDoTask()
    this.getTableData()
  },
  methods: {
    // 渲染按钮操作栏
    renderBtnsBar (h) {
      // 按钮通用属性填充
      const btnBars = [
        {
          label: '导出',
          loading: this.btnLoading.export,
          method: this.handleExport,
          hasAuth: true
        }
      ]
      return getListPageBtnsBar(h, btnBars, this.showBtn, 'start')
    },
    // 渲染表格操作栏按钮
    renderTableBtnAction (h, { row }) {
      const viewBtn = { label: '查看', method: this.handleView }
      const editBtn = { label: '编辑', method: this.handleEdit, }
      const finishBtn = { label: '开发完成', method: this.handleDevelopFinish }
      const auditBtn = { label: '审核', method: this.handleAudit }
      const cancelBtn = { label: '计划取消', method: this.handlePlanCancel }
      const packupBtn = {
        label: '取回',
        method: this.handlePackup,
        confirmTitle: '确定要取回当前单据吗？'
      }
      const btnMaps = {
        [RECORD_STATUS_VALUES.ToSubmit]: [viewBtn, editBtn, cancelBtn],
        [RECORD_STATUS_VALUES.ToAudit]: [viewBtn, auditBtn, packupBtn],
        [RECORD_STATUS_VALUES.ToDevelop]: [viewBtn, editBtn, finishBtn, cancelBtn],
        [RECORD_STATUS_VALUES.Canceled]: [viewBtn],
        [RECORD_STATUS_VALUES.Finshed]: [viewBtn]
      }
      const actionList = btnMaps[row.status] ?? []
      return getTableAction({ h, row, actionList, showBtn: this.showBtn })
    },
    // 处理代办事项
    executeToDoTask () {
      const { status } = this.$route?.query
      if (!status) return
      const index = FORM_ITEMS.findIndex(item => item.prop == 'status')
      index > -1 && this.formItems.splice(index, 1)
      this.formData = { ...getInitFormData(this.formItems), status }
    },
    // 获取表列
    getTableColumns () {
      const columns = [...TABLE_COLUMNS]
      const statusIndex = columns.findIndex(item => item.key == 'statusStr')
      if (statusIndex > -1) columns[statusIndex] = getStatusColumn(this.handleToOAView)
      const inspectionNoIndex = columns.findIndex(item => item.key == 'supplierInspectionNo')
      if (statusIndex > -1) columns[inspectionNoIndex] = getSupplierInspectionNoColumn(this.redirectSupplierInspectionNoPage)
      return columns
    },
    // 获取查询入参
    getSearchParams () {
      const { progressStatus } = this.$route?.query // 代办临期参数
      const params = {
        ...this.formData,
        ...this.paginationParams,
        progressStatus
      }
      return params
    },
    // 获取表格数据 by 查询表单
    async getTableData () {
      setAuthBtnId('查询')
      const data = this.getSearchParams()
      const res = await getPagerService(data, this.TableInfo.setLoading)
      if (res?.retData) {
        this.TableInfo.setList(res.retData.results)
        this.setTotalNum(res.retData.totalNum)
      }
    },
    // 获取品类集合
    setFormCateUuids (list) {
      this.formData.categoryUuids = list.map(item => item.categoryUuid)
    },
    // 导出
    async handleExport () {
      setAuthBtnId('查询')
      const data = this.formData
      const loadingFn = state => { this.btnLoading.export = state }
      const res = await devPlanExportService(data, loadingFn)
      createExcelByExport({ excelTitle: `开发计划_${generateUuid()}`, res })
    },
    // 查看
    handleView (row) {
      let routerName = 'developPlanView'
      if (row.status == RECORD_STATUS_VALUES.Finshed) {
        routerName = 'developPlanFinishView'
      }
      const { href } = this.$router.resolve({
        name: routerName,
        query: { planNo: row.planNo }
      })
      window.open(href, '_blank')
    },
    // 编辑
    handleEdit (row) {
      this.$router.push({
        name: 'developPlanEdit',
        query: { planNo: row.planNo }
      })
    },
    // 审核
    handleAudit (row) {
      this.fetchAndRedirectOa(row.workflowRequestId)
    },
    // 取回
    async handlePackup (row) {
      const data = { recordNo: row.recordNo }
      const res = await getBackWorkflow4DevPlanService(data, this.TableInfo.setLoading)
      if (isResponseSuccess(res)) {
        this.$message.success('取回成功')
        this.getTableData()
      }
    },
    // 计划取消
    async handlePlanCancel (row) {
      this.planCancel.planNo = row.planNo
      this.planCancel.visible = true
    },
    // 开发完成
    handleDevelopFinish (row) {
      this.$router.push({
        name: 'developPlanFinish',
        query: { planNo: row.planNo }
      })
    },
    // 进入OA查看页面
    handleToOAView (row) {
      const { href } = this.$router.resolve({
        name: 'developPlanOaView',
        query: { recordNo: row.recordNo }
      })
      window.open(href, '_blank')
    },
    // 请求并跳转OA
    async fetchAndRedirectOa (oaRequestId) {
      const data = { oaRequestId }
      const retData = await getToSkipOAUrlService(data, this.TableInfo.setLoading)
      if (retData) window.open(retData)
    },
    // 跳转供应商单号页面
    async redirectSupplierInspectionNoPage (reportCode) {
      const retData = await this.getSupplierInspectionDetails(reportCode)
      if (retData) {
        const { planId, supplierId, targetList } = retData
        this.$router.push({ name: 'viewReport', query: { planId, supplierId, targetList } })
      }
    },
    // 获取供应商单号详情
    async getSupplierInspectionDetails (reportCode) {
      const data = { reportCode }
      const res = await getSupplierInspectionByReportCodeService(data, this.TableInfo.setLoading)
      return res?.retData
    },
    // 取消开发请求
    async confirmPlanCancel (cancelReason) {
      const data = { cancelReason, planNo: this.planCancel.planNo }
      const loadingFn = state => { this.planCancel.loading = state }
      const res = await cancelService(data, loadingFn)
      if (isResponseSuccess(res)) {
        this.$message.success('操作成功')
        this.planCancel.visible = false
        this.getTableData()
      }
    },
  }
}
</script>
